// https://leetcode.cn/problems/combination-sum/description/

// 算法思路总结：
// 1. 回溯算法求解组合总和问题（可重复使用元素）
// 2. 每个元素有两种选择：使用当前元素（可重复）或跳过当前元素
// 3. 使用sum变量维护当前路径和，等于target时保存结果
// 4. 剪枝：当sum超过target时提前返回
// 5. 时间复杂度：O(2^target)，空间复杂度：O(target/min(candidates))

#include <iostream>
using namespace std;

#include <cstring>
#include <vector>
#include <algorithm>

class Solution 
{
public:
    vector<vector<int>> ret;
    vector<int> path;
    int _target;
    int sum;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) 
    {
        sum = 0;
        ret.clear();
        _target = target;

        dfs(0, candidates);

        return ret;
    }

    void dfs(int pos, vector<int>& candidates)
    {
        if (sum == _target)
        {
            ret.push_back(path);
            return ;
        }

        if (pos == candidates.size() || sum > _target)
        {
            return ;
        }

        sum += candidates[pos];
        path.push_back(candidates[pos]);
        dfs(pos, candidates);
        sum -= candidates[pos];
        path.pop_back();

        dfs(pos + 1, candidates);
    }
};

void printResult(const vector<vector<int>>& result) 
{
    cout << "[";
    for (int i = 0; i < result.size(); ++i) 
    {
        cout << "[";
        for (int j = 0; j < result[i].size(); ++j) 
        {
            cout << result[i][j];
            if (j < result[i].size() - 1) cout << ",";
        }
        cout << "]";
        if (i < result.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

int main()
{
    vector<int> nums1 = {2,3,6,7}, nums2 = {2,3,5};
    int target1 = 7, target2 = 8;

    Solution sol;

    auto vv1 = sol.combinationSum(nums1, target1);
    auto vv2 = sol.combinationSum(nums2, target2);

    printResult(vv1);
    printResult(vv2);

    return 0;
}